#include "thread_manager.h"
#include "host.h"
#include <math.h>
rt_int32_t temp_list[16];
rt_int32_t temp_avg;
rt_uint16_t slaver_online_status;

static void print_temp_info(void)
{
    static rt_uint8_t print_skip;
    rt_int32_t temp_max, temp_min;
    rt_uint8_t temp_max_min_init = 0;
    if(print_skip++ >= (1000 / HOST_THREAD_CIRCLE))
    {
        print_skip = 0;

        rt_kprintf("temp list:\n");
        for(rt_uint8_t i = 0; i < 16; i++)
        {
            if(slaver_online_status & (1 << i)) 
            {
                if(temp_max_min_init == 0) 
                {
                    temp_max_min_init = 1;
                    temp_max = temp_list[i];
                    temp_min = temp_list[i];
                }
                if(temp_max < temp_list[i])
                {
                    temp_max = temp_list[i];
                }
                if(temp_min > temp_list[i])
                {
                    temp_min = temp_list[i];
                }
                rt_kprintf("【%d】\t\t%d\r\n", i, temp_list[i]);
            }
        }
        rt_kprintf("【avg】\t\t%d\r\n", temp_avg); 
        rt_kprintf("【Range】\t%d\r\n\n", temp_max - temp_min);
    }
}
static void get_temp_info(void)
{
    rt_int32_t sensor_temp_sum;
    rt_uint8_t slaver_num;

    sensor_temp_sum = 0;
    slaver_num = 0;
    slaver_online_status = rt_atomic_load(&slaver_online);

    for(rt_uint8_t i = 0; i < 16; i++)
    {
        if(slaver_online_status & (1 << i))
        {
            slaver_num++;
            temp_list[i] = rt_atomic_load(&sensor_temp[i]);
            sensor_temp_sum += temp_list[i];
        }
    }
    temp_avg = (slaver_num > 0) ? sensor_temp_sum / slaver_num : 0;
}
static void host_thread_entry(void *parameter)
{

    while(1)
    {
        host_listen();
        get_temp_info();
        host_mode();
        print_temp_info();
        rt_thread_mdelay(HOST_THREAD_CIRCLE);
    }
}
int host_thread_init(void)
{
    rt_thread_t tid;

    host_init();

    tid = rt_thread_create("host", host_thread_entry, RT_NULL, 4096, 6, 50);
    if(tid != RT_NULL)
    {
        rt_thread_startup(tid);
    }
        
    return 0;
}